import React, {useEffect, useState} from 'react';
import {Req} from '../../util/fetch';
import {
    BarChart2,
    Building2,
    ChevronRight,
    Edit2,
    Eye,
    FileText,
    Heart,
    Megaphone,
    MessageSquare,
    PartyPopper,
    Snowflake,
    Sun,
    Tag,
    Target,
    Trash2,
    Users,
    Zap
} from 'lucide-react';
import {useNavigate, useParams} from 'react-router-dom';
import EditTrainingModal from "../../components/modals/EditTrainingModal";
import StatsModal from "../../components/modals/StatsModal";
import MediaManageModal from "../../components/modals/MediaManageModal";
import TagManageModal from "../../components/modals/TagManageModal";
import CommentManageModal from "../../components/modals/CommentManageModal";
import DocumentManageModal from "../../components/modals/DocumentManageModal";
import UserManageModal from "../../components/modals/UserManageModal";
import DeleteConfirmModal from "../../components/modals/DeleteConfirmModal";

interface Category {
    id: string;
    name: string;
    icon: React.ReactNode;
    color: string;
}

interface Training {
    id: number;
    title: string;
    subTitle: string;
    startDate: string;
    endDate: string;
    place: string;
    organizerName: string;
    participants: number;
    views: number;
    status: '0' | '1' | '2';
    cover: string;
    tags: string;
}

const categories: Category[] = [
    {
        id: 'dealer-meeting',
        name: '分销商会议',
        icon: <Building2 className="w-6 h-6"/>,
        color: 'from-purple-500 to-purple-600'
    },
    {
        id: 'ice-sword',
        name: '寒冰亮剑',
        icon: <Snowflake className="w-6 h-6"/>,
        color: 'from-cyan-500 to-cyan-600'
    },
    {
        id: 'customer-thanks',
        name: '客户答谢会',
        icon: <Heart className="w-6 h-6"/>,
        color: 'from-pink-500 to-pink-600'
    },
    {
        id: 'new-year',
        name: '新春年会',
        icon: <PartyPopper className="w-6 h-6"/>,
        color: 'from-red-500 to-red-600'
    },
    {
        id: 'spring-thunder',
        name: '春雷行动',
        icon: <Zap className="w-6 h-6"/>,
        color: 'from-blue-500 to-blue-600'
    },
    {
        id: '520-roadshow',
        name: '520路演',
        icon: <Megaphone className="w-6 h-6"/>,
        color: 'from-indigo-500 to-indigo-600'
    },
    {
        id: 'sunshine',
        name: '骄阳行动',
        icon: <Sun className="w-6 h-6"/>,
        color: 'from-orange-500 to-orange-600'
    },
    {
        id: 'target-sprint',
        name: '目标冲刺动员',
        icon: <Target className="w-6 h-6"/>,
        color: 'from-green-500 to-green-600'
    }
];

export default function AdminCategories() {
    const navigate = useNavigate();
    const {categoryId} = useParams();
    const [trainings, setTrainings] = useState<Training[]>([]);
    const [selectedTraining, setSelectedTraining] = useState<Training | null>(null);
    const [showEditModal, setShowEditModal] = useState(false);
    const [showStatsModal, setShowStatsModal] = useState(false);
    const [showMediaModal, setShowMediaModal] = useState(false);
    const [showTagModal, setShowTagModal] = useState(false);
    const [showCommentModal, setShowCommentModal] = useState(false);
    const [showDocumentModal, setShowDocumentModal] = useState(false);
    const [showUserModal, setShowUserModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);

    const currentCategory = categories.find(cat => cat.id === categoryId);

    const getStatusStyle = (status: Training['status']) => {
        switch (status) {
            case '1':
                return 'bg-green-100 text-green-600';
            case '0':
                return 'bg-yellow-100 text-yellow-600';
            case '2':
                return 'bg-blue-100 text-blue-600';
            default:
                return 'bg-gray-100 text-gray-600';
        }
    };

    const queryList = async (id) => {
        const res = await Req(`/bsTrain/list?from=back&category=${id ? id : categoryId}`)
        if (res.success) {
            setTrainings(res.data)
        } else {
            alert(res.message)
        }
    };

    const getStatusText = (status: Training['status']) => {
        switch (status) {
            case '1':
                return '已发布';
            case '0':
                return '草稿';
            case '2':
                return '已完成';
            default:
                return '未知状态';
        }
    };

    const handleDelete = async (id: number) => {
        await Req(`/bsTrain/batch?ids=${id}`, {method: 'DELETE'});
        queryList(null)
        setShowDeleteModal(false);
    };

    const handleSaveUsers = async (updatedUsers: any) => {
        console.log('handleSaveUsers', updatedUsers);
        const res = await Req('/bsTrainPerson/add', {
            method: 'POST',
            body: {
                trainId: selectedTraining.id,
                list: updatedUsers
            },
            headers: undefined
        })
        if (res.success) {
            alert(res.message)
            queryList(null)
            setShowUserModal(false);
        } else {
            alert(res.message)
        }
    };

    const handleSaveTags = async (updatedTags: string[]) => {
        const res = await Req('/bsTrain/edit', {
            method: 'PUT',
            body: {
                id: selectedTraining.id,
                tags: updatedTags.join(',')
            },
            headers: undefined
        })
        if (res.success) {
            alert(res.message)
            queryList(null)
            setShowTagModal(false);
        } else {
            alert(res.message)
        }
    };

    useEffect(() => {
        if (currentCategory) {
            queryList(null)
        }
    }, [])

    if (!currentCategory) {
        return (
            <div className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    {categories.map(category => (
                        <button
                            key={category.id}
                            onClick={() => {
                                navigate(`/admin/categories/${category.id}`)
                                queryList(category.id)
                            }}
                            className="bg-white p-6 rounded-xl shadow-sm hover:shadow-md transition-all duration-300 text-left group"
                        >
                            <div className={`w-14 h-14 rounded-2xl bg-gradient-to-br ${category.color} 
                flex items-center justify-center text-white shadow-lg 
                transform transition-all duration-300 group-hover:scale-110 group-hover:rotate-3`}
                            >
                                {category.icon}
                            </div>
                            <h3 className="text-lg font-semibold mt-4 mb-2">{category.name}</h3>
                            <div className="flex items-center text-gray-500 group-hover:text-blue-500">
                                <span>查看训练列表</span>
                                <ChevronRight className="w-5 h-5 ml-1"/>
                            </div>
                        </button>
                    ))}
                </div>
            </div>
        );
    }

    return (
        <div className="p-6">
            <div className="mb-6">
                <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                        <div className={`w-12 h-12 rounded-xl bg-gradient-to-br ${currentCategory.color} 
              flex items-center justify-center text-white shadow-lg`}
                        >
                            {currentCategory.icon}
                        </div>
                        <h2 className="text-2xl font-bold">{currentCategory.name}</h2>
                    </div>
                    <button
                        onClick={() => navigate(`/admin/trainings/new?category=${categoryId}`)}
                        className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                    >
                        添加训练
                    </button>
                </div>
            </div>

            <div className="bg-white rounded-xl shadow-sm overflow-hidden">
                <table className="w-full">
                    <thead>
                    <tr className="bg-gray-50 border-b">
                        <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">训练信息</th>
                        <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">时间</th>
                        <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">地点</th>
                        <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">组织者</th>
                        <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">参与人数</th>
                        <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">状态</th>
                        <th className="px-6 py-4 text-right text-sm font-medium text-gray-500">操作</th>
                    </tr>
                    </thead>
                    <tbody className="divide-y">
                    {trainings.map(training => (
                        <tr key={training.id} className="hover:bg-gray-50">
                            <td className="px-6 py-4">
                                <div className="flex items-center">
                                    <img
                                        src={training.cover}
                                        className="w-12 h-12 rounded object-cover mr-3"
                                    />
                                    <div>
                                        <div className="font-medium text-gray-900">{training.title}</div>
                                        <div className="text-sm text-gray-500">{training.subTitle}</div>
                                    </div>
                                </div>
                            </td>
                            <td className="px-6 py-4 text-gray-500">
                                {training.startDate} 至<br/>{training.endDate}
                            </td>
                            <td className="px-6 py-4 text-gray-500">{training.place}</td>
                            <td className="px-6 py-4 text-gray-500">{training.organizerName}</td>
                            <td className="px-6 py-4 text-gray-500">{training.participants}</td>
                            <td className="">
                              <span className={`px-3 py-1 rounded-full text-sm ${getStatusStyle(training.status)}`}>
                                {getStatusText(training.status)}
                              </span>
                            </td>
                            <td className="px-6 py-4">
                                <div className="flex items-center justify-end space-x-2">
                                    <button
                                        onClick={() => {
                                            console.log(training)
                                            setSelectedTraining(training);
                                            setShowEditModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        title="基础信息"
                                    >
                                        <Edit2 className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => {
                                            setSelectedTraining(training);
                                            setShowStatsModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        title="浏览统计"
                                    >
                                        <BarChart2 className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => {
                                            setSelectedTraining(training);
                                            setShowUserModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        title="人员管理"
                                    >
                                        <Users className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => {
                                            setSelectedTraining(training);
                                            setShowMediaModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        title="媒体管理"
                                    >
                                        <Eye className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => {
                                            setSelectedTraining(training);
                                            setShowTagModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        title="标签管理"
                                    >
                                        <Tag className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => {
                                            setSelectedTraining(training);
                                            setShowCommentModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        title="评论管理"
                                    >
                                        <MessageSquare className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => {
                                            setSelectedTraining(training);
                                            setShowDocumentModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                        title="资料管理"
                                    >
                                        <FileText className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => {
                                            setSelectedTraining(training);
                                            setShowDeleteModal(true);
                                        }}
                                        className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                        title="删除"
                                    >
                                        <Trash2 className="w-5 h-5"/>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>

            {/* 编辑训练模态框 */}
            {selectedTraining && showEditModal && (
                <EditTrainingModal
                    training={selectedTraining}
                    onClose={() => {
                        setShowEditModal(false);
                        setSelectedTraining(null);
                    }}
                    onSave={async (updatedTraining) => {
                        updatedTraining.uptTime = null
                        updatedTraining.crtTime = null
                        const res = await Req('/bsTrain/edit', {
                            method: 'PUT',
                            body: updatedTraining,
                            headers: undefined
                        })
                        if (res.success) {
                            setShowEditModal(false);
                            queryList(null)
                            alert(res.message)
                        } else {
                            alert(res.message)
                        }
                    }}
                />
            )}

            {/* 统计模态框 */}
            {selectedTraining && showStatsModal && (
                <StatsModal
                    training={selectedTraining}
                    onClose={() => {
                        setShowStatsModal(false);
                        setSelectedTraining(null);
                    }}
                />
            )}

            {/* 媒体管理模态框 */}
            {selectedTraining && showMediaModal && (
                <MediaManageModal
                    training={selectedTraining}
                    onClose={() => {
                        setShowMediaModal(false);
                        setSelectedTraining(null);
                    }}
                />
            )}

            {/* 标签管理模态框 */}
            {selectedTraining && showTagModal && (
                <TagManageModal
                    title={selectedTraining.title}
                    tags={selectedTraining.tags?.split(',') || []}
                    onClose={() => {
                        setShowTagModal(false);
                        setSelectedTraining(null);
                    }}
                    onSave={handleSaveTags}
                />
            )}

            {/* 评论管理模态框 */}
            {selectedTraining && showCommentModal && (
                <CommentManageModal
                    training={selectedTraining}
                    onClose={() => {
                        setShowCommentModal(false);
                        setSelectedTraining(null);
                    }}
                />
            )}

            {/* 资料管理模态框 */}
            {selectedTraining && showDocumentModal && (
                <DocumentManageModal
                    training={selectedTraining}
                    onClose={() => {
                        setShowDocumentModal(false);
                        setSelectedTraining(null);
                    }}
                />
            )}

            {/* 人员管理模态框 */}
            {selectedTraining && showUserModal && (
                <UserManageModal
                    mode="edit"
                    training={selectedTraining}
                    onClose={() => {
                        setShowUserModal(false);
                        setSelectedTraining(null);
                    }}
                    onSave={handleSaveUsers}
                />
            )}

            {/* 删除确认模态框 */}
            {selectedTraining && showDeleteModal && (
                <DeleteConfirmModal
                    title="删除训练"
                    message={`确定要删除"${selectedTraining.title}"吗？此操作不可恢复。`}
                    onConfirm={() => handleDelete(selectedTraining.id)}
                    onCancel={() => {
                        setShowDeleteModal(false);
                        setSelectedTraining(null);
                    }}
                />
            )}
        </div>
    );
}